<?php

require_once($GLOBALS['cfgPaths']['lib'] . 'cms/elements.o.inc.php');
require_once($GLOBALS['cfgPaths']['absPath'] . 'etc/var_queries.inc.php');
require_once($GLOBALS['cfgPaths']['lib'] . 'model2/tagsupport/dbaCMSObjectTags.o.inc.php');

class dbaCMSDeploy {

    function dbaCMSDeploy(&$dba, $langtable = array()) {
        $this->dba = &$dba;
        $this->langtable = $langtable;
    }

    function getPubDocIdArray($site) {
        $ids = array();
        if ($site) {
            $sth = $this->dba->query("select id from " . $this->dba->tableforwarder . "_cmsPubDoc  where site_id=$site and parent_id!=0;");
            if (is_object($sth)) {
                $rows = $sth->fetch_rows();
                for ($i = 0; $i < count($rows); $i++) {
                    $ids[] = $rows[$i][0];
                }
            }
        }
        return $ids;
    }

    function getPubDocByPath($path, $site_id) {
        if ($site_id && $path) {
            $site_id = (int) $site_id;
            $sth = $this->dba->query("select * from " . $this->dba->tableforwarder . "_cmsPubDoc where doc_path=" . $this->dba->quote($path) . " and site_id=$site_id;");
            if (is_object($sth)) {
                $out = $sth->fetch_row_Array();
                $sth->free();
                return $out;
            }
        }
    }

    function getPubDocIdArrayExport($site) {
        $ids = array();
        if ($site) {
            $sth = $this->dba->query("select id from " . $this->dba->tableforwarder . "_cmsPubDoc  where site_id=$site and " .
                            "parent_id!=0 and type != 'folder' and type != 'inc';");
            if (is_object($sth)) {
                $rows = $sth->fetch_rows();
                for ($i = 0; $i < count($rows); $i++) {
                    $ids[] = $rows[$i][0];
                }
            }
        }
        return $ids;
    }

    function getSiteRootId($site_id) {
        $sth = $this->dba->query("select id from " . $this->dba->tableforwarder . "_cmsDoc where parent_id=0 and site_id=$site_id;");
        if (is_object($sth)) {
            $row = $sth->fetch_row();
            $sth->free();
            return $row[0];
        }
    }

    // Home einer Site finden
    function getSitePubHomeId($site_id) {
        if ($site_id) {
            $siteroot = $this->getSiteRootId($site_id);
            $sth = $this->dba->query("select id from " . $this->dba->tableforwarder . "_cmsPubDoc where parent_id='$siteroot' and name='index';");
            if (is_object($sth)) {
                $row = $sth->fetch_row();
                $sth->free();
                return $row[0];
            }
        }
    }

    function getCompletePubDoc($id, $lang) {
        $cmsdba = new dbaCMSObjectTags($this->dba);
        if (!$lang || !$id)
            return;
        $sth = $this->dba->query("select * from " . $this->dba->tableforwarder . "_cmsPubDoc where id=$id;");
        if (is_object($sth) && $sth->num_rows()) {
            $doc = $sth->fetch_row_Array();
            $sth->free();
            // elements holen
            $fieldStr = "type,idx,parent_id,id,name";
            $sth = $this->dba->query("select $fieldStr from " . $this->dba->tableforwarder . "_cmsPubElement where doc_id=$id order by idx;");
            if (is_object($sth)) {
                $elements = $sth->fetch_rows_Array();
                $sth->free();
            }
            for ($i = 0; $i < count($elements); $i++) {
                if ($elements[$i]['type'] != 'template') {
                    if (isset($GLOBALS['cfgQueries'][$elements[$i]['type']]['query']['pub']))
                        $sth = $this->dba->query($GLOBALS['cfgQueries'][$elements[$i]['type']]['query']['pub'] . " and lang='$lang' AND element_id=" . $elements[$i]['id'] . ";");
                    else
                        $sth = $this->dba->query("select * from " . $this->dba->tableforwarder . "_cmsPubType_" . $elements[$i]['type'] . " where lang='$lang' AND element_id=" . $elements[$i]['id'] . ";");
                    if (is_object($sth)) {
                        $elements[$i]['data'] = $sth->fetch_row_Array();
                        $sth->free();
                        $attribs = $cmsdba->getCategoriesAsAttributes($elements[$i]['id'], $elements[$i]['type']);
                        if (is_array($attribs))
                            foreach ($attribs as $n => $v) {
                                $elements[$i]['data']["attr_" . $n] = $v;
                            }
                    }
                } // if template
            } // for
            $doc['elements'] = new elements($elements, 'id', 'parent_id', 'name');
            return $doc;
        }
    }

    function getLocationObjects($id, $name, $lang) {
        $this->getPubLocationObjects($id, $name, $lang);
    }

    /**
     * Get published Location
     *
     * @param int $id Document id.
     * @param string $name Location name
     * @param int $lang Lang id
     */
    function getPubLocationObjects($id, $name, $lang) {
        $cmsdba = new dbaCMSObjectTags($this->dba);
        if (!$lang || !$id)
            return;
        $sth = $this->dba->query("select * from " . $this->dba->tableforwarder . "_cmsPubDoc where id=$id;");
        if (is_object($sth) && $sth->num_rows()) {
            $doc = $sth->fetch_row_Array();
            $sth->free();
            // elements holen
            $fieldStr = "type,idx,parent_id,id,name";
            $sth = $this->dba->query("select $fieldStr from " . $this->dba->tableforwarder . "_cmsPubElement where doc_id=$id and name='$name' order by idx;");
            if (is_object($sth)) {
                $elements = $sth->fetch_rows_Array();
                $sth->free();
            }
            for ($i = 0; $i < count($elements); $i++) {
                if ($elements[$i]['type'] != 'template') {
                    if (isset($GLOBALS['cfgQueries'][$elements[$i]['type']]['query']['pub']))
                        $sth = $this->dba->query($GLOBALS['cfgQueries'][$elements[$i]['type']]['query']['pub'] . " and lang='$lang' AND element_id=" . $elements[$i]['id'] . ";");
                    else
                        $sth = $this->dba->query("select * from " . $this->dba->tableforwarder . "_cmsPubType_" . $elements[$i]['type'] . " where lang='$lang' AND element_id=" . $elements[$i]['id'] . ";");
                    if (is_object($sth)) {
                        $elements[$i]['data'] = $sth->fetch_row_Array();
                        $sth->free();
                        $attribs = $cmsdba->getCategoriesAsAttributes($elements[$i]['id'], $elements[$i]['type']);
                        if (is_array($attribs))
                            foreach ($attribs as $n => $v) {
                                $elements[$i]['data']["attr_" . $n] = $v;
                            }
                    }
                } // if template
            } // for
            return $elements;
        }
    }

    function getPubDocsBySite($siteid) {
        $sth = $this->dba->query("select "
                        . $this->dba->tableforwarder . "_cmsPubDoc.id,"
                        . $this->dba->tableforwarder . "_cmsPubDoc.weighting,"
                        . $this->dba->tableforwarder . "_cmsPubDoc.name,"
                        . $this->dba->tableforwarder . "_cmsPubDoc.parent_id,"
                        . $this->dba->tableforwarder . "_cmsPubDoc.type,"
                        . $this->dba->tableforwarder . "_cmsPubDoc.nav_visible,"
                        . $this->dba->tableforwarder . "_cmsPubDoc.sitemap_visible,"
                        . $this->dba->tableforwarder . "_cmsPubDoc.publishtype,"
                        . $this->dba->tableforwarder . "_cmsPubDoc.headertpl,"
                        . $this->dba->tableforwarder . "_cmsPubDoc.contenttpl,"
                        . $this->dba->tableforwarder . "_cmsPubDoc.footertpl from "
                        . $this->dba->tableforwarder . "_cmsPubDoc left join "
                        . $this->dba->tableforwarder . "_cmsDoc using (id) order by name;");
        if (is_object($sth)) {
            $out = $sth->fetch_rows_Array();
            $sth->free();
            return $out;
        }
    }

    // s.o.
    function getPubDocDescrTree($lang, $site_id = 0) {
        $bySiteStr = '';
        if ($site_id) {
            $bySiteStr = "site_id=$site_id and ";
        }
        $sth = $this->dba->query("select distinct D.*, DD.descr, DD.lang from "
                        . $this->dba->tableforwarder . "_cmsPubDoc D left join "
                        . $this->dba->tableforwarder . "_cmsPubLang L on (D.id=L.doc_id) left join "
                        . $this->dba->tableforwarder . "_cmsPubDocDescription DD on (D.id=DD.doc_id) where "
                        . " $bySiteStr((lang_id=$lang and lang=$lang) or D.parent_id=0 or D.type = 'folder') and parent_id!=0 order by D.weighting desc,descr;");
        if (is_object($sth)) {
            $out = $sth->fetch_rows_Array();
            $sth->free();
            return $out;
        }
    }

    /* Alte Version ohne cmsPubLang -----
      // s.o.
      function getPubDocDescrTree ($lang)
      {
      $sth = $this->dba->query("select * from ".$this->dba->tableforwarder."_cmsPubDoc,".$this->dba->tableforwarder."_cmsDocDescription where id=doc_id AND lang='$lang' order by weighting desc,descr;");
      if (is_object($sth))
      {
      $out = $sth->fetch_rows_Array();
      $sth->free();
      return $out;
      }
      }
     */

    function getPubDocs() {
        $sth = $this->dba->query("select * from " . $this->dba->tableforwarder . "_cmsPubDoc order by name;");
        if (is_object($sth)) {
            $out = $sth->fetch_rows_Array();
            $sth->free();
            return $out;
        }
    }

    // TODO Rausfinden, ob diese Methode macht, was die andere machen sollte
    function getPubDocsBySite2($site) {
        $sth = $this->dba->query("select * from " . $this->dba->tableforwarder . "_cmsPubDoc where site_id=$site order by name;");
        if (is_object($sth)) {
            $out = $sth->fetch_rows_Array();
            $sth->free();
            return $out;
        }
    }

    // $clause: Rest der Query ab where
    function getContentObjectsByCat($cats, $clause) {
        $sth = $this->dba->query("select allowed_type from " . $this->dba->tableforwarder .
                        "_cmsObjCat where id='" . $cats[0] . "';");
        if (is_object($sth) && $sth->num_rows()) {
            $catstr = "(cat_id='" . join("' or cat_id='", $cats) . "')";
            $type = $sth->fetch_row();
            $sth->free();
            $sth = $this->dba->query("select distinct Type.element_id from " . $this->dba->tableforwarder .
                            "_cmsPubType_" . $type[0] . " As Type, " . $this->dba->tableforwarder .
                            "_cmsElementObjCat As Element where Type.element_id=Element.element_id and " .
                            "$catstr $clause;");
            if (is_object($sth)) {
                $rows = $sth->fetch_rows();
                $sth->free();
                $res = array();
                for ($i = 0; $i < count($rows); $i++) {
                    $res[] = $rows[$i][0];
                }
                return $res;
            }
        }
    }

    function getPubDoc($id) {
        $sth = $this->dba->query("select * from " . $this->dba->tableforwarder . "_cmsPubDoc where id=$id order by name;");
        if (is_object($sth)) {
            $out = $sth->fetch_row_Array();
            $sth->free();
            return $out;
        }
    }

    function getPubDocByName($name, $site_id) {
        if ($site_id && $name) {
            $sth = $this->dba->query("select * from " . $this->dba->tableforwarder . "_cmsPubDoc where name=" . $this->dba->quote($name) . " and site_id=$site_id;");
            if (is_object($sth)) {
                $out = $sth->fetch_row_Array();
                $sth->free();
                return $out;
            }
        }
    }

    function getPubDocIdByName($name, $site_id) {
        if ($site_id && $name) {
            $sth = $this->dba->query("select id from " . $this->dba->tableforwarder . "_cmsPubDoc where name=" . $this->dba->quote($name) . " and site_id=$site_id;");
            if (is_object($sth)) {
                $row = $sth->fetch_row();
                $sth->free();
                return $row[0];
            }
        }
    }

    function isPublishedDoc($doc_id) {
        $sth = $this->dba->query("select id from " . $this->dba->tableforwarder . "_cmsPubDoc where id='$doc_id';");
        if (is_object($sth) && $sth->num_rows()) {
            $sth->free();
            return true;
        }
    }

    function getPubDocParent($doc_id) {
        $sth = $this->dba->query("select parent_id from " . $this->dba->tableforwarder . "_cmsPubDoc where id='$doc_id';");
        if (is_object($sth)) {
            $num_rows = $sth->num_rows();
            if (!$num_rows) {
                $sth->free();
                return -1;
            }
            $dset = $sth->fetch_row();
            $sth->free();
            return $dset[0];
        } else
            return -1;
    }

    function getPublishedIDs() {
        $sth = $this->dba->query("select id from " . $this->dba->tableforwarder . "_cmsPubDoc;");
        if (is_object($sth)) {
            $sets = $sth->fetch_rows();
            $sth->free();
            for ($i = 0; $i < count($sets); $i++) {
                $a[] = $sets[$i][0];
            }
            return $a;
        }
    }

    function getTypes() {
        $sth = $this->dba->query("select * from " . $this->dba->tableforwarder . "_cmsType;");
        if ($sth) {
            $rows = $sth->fetch_rows_Array();
            $sth->free();
            return $rows;
        }
    }

    function getImage($id) {
        $sth = $this->dba->query("select * from " . $this->dba->tableforwarder . "_cmsImg where id='$id';");
        if ($sth) {
            return $sth->fetch_row_Array();
        }
    }

    function siteSearch($site_id, $lang, $searchstr) {
        return $this->dba->query("select doc_id,doc_title,doc_description from " . $this->dba->tableforwarder . "_cmsSearchIndex where match (doc_title, doc_description, doc_body) against (" . $this->dba->quote($searchstr) . ") and lang='$lang' and site_id='$site_id';");
    }

    function selectContentObjects($type, $clause, $lang, $orderby, $offset, $limit, $cats = array(), $site_id = null, $doc_id = null, $showquery = false) {
        $this->selectPubContentObjects($type, $clause, $lang, $orderby, $offset, $limit, $cats, $site_id, $doc_id, $showquery);
    }

    // $clause: Rest der Query ab where
    function selectPubContentObjects($type, $clause, $lang, $orderby, $offset, $limit, $cats = array(), $site_id = null, $doc_id = null, $showquery = false) {
        if ($orderby)
            $orderby = " order by " . $orderby;
        $withCats = (count($cats) > 0);
        if ($withCats)
            $catstr = "(cat_id='" . join("' or cat_id='", $cats) . "')";
        $site_from = '';
        $site_where = '';
        if ($site_id) {
            $site_from = ", " . $this->dba->tableforwarder . "_cmsPubDoc D ";
            $site_where = " and E.doc_id=D.id and D.site_id=" . (int) $site_id . " ";
        }
        $sth = $this->dba->query("select distinct T.*,E.doc_id from " . $this->dba->tableforwarder .
                        "_cmsPubType_" . $type . " T, " . $this->dba->tableforwarder .
                        "_cmsPubElement E" . $site_from .
                        ($withCats ? "," . $this->dba->tableforwarder . "_cmsElementObjCat As C" : "") .
                        " where E.id = T.element_id" .
                        ($withCats ? " and C.element_id=T.element_id and " . $catstr : "") .
                        " and lang=" . (int) $lang .
                        (empty($clause) ? "" : " and (" . $clause . ")") . ($doc_id ? ' and E.doc_id=' . (int) $doc_id : '') . $site_where . $orderby . ";", $showquery);
        if ($this->dba->getErrorNo())
                print $this->dba->getError();
        if (is_object($sth) && $num_rows = $sth->num_rows()) {
            $offset = $offset ? (int) $offset : 0;
            $sth->setCursor($offset);
            $objects = array();
            $limit = $limit ? $limit : 18446744073709551615;
            $limit = $limit > $num_rows - $offset ? $num_rows - $offset : $limit;
            for ($i = 0; $i < $limit; $i++)
                $objects[] = $sth->fetch_row_array();
            $sth->free();
            return array('data' => $objects, 'count' => $num_rows);
        }
    }

    // $clause: Rest der Query ab where
    function selectPubContentObjects2($type, $clause, $lang, $orderby, $offset, $limit, $cats = array(), $site_id = null, $doc_id = null, $showquery = false) {
        if ($orderby)
            $orderby = " order by " . $orderby;
        $sth = $this->dba->query("select distinct T.*,E.doc_id from " . $this->dba->tableforwarder .
                        "_cmsPubType_" . $type . " T, " . $this->dba->tableforwarder .
                        "_cmsPubElement E where E.id = T.element_id and lang=" . (int) $lang .
                        (empty($clause) ? "" : " and (" . $clause . ")") . $orderby . ";");
        if (is_object($sth) && $num_rows = $sth->num_rows()) {
            $offset = $offset ? (int) $offset : 0;
            $sth->setCursor($offset);
            $objects = array();
            $limit = $limit ? $limit : 18446744073709551615;
            $limit = $limit > $num_rows - $offset ? $num_rows - $offset : $limit;
            for ($i = 0; $i < $limit; $i++)
                $objects[] = $sth->fetch_row_array();
            $sth->free();
            return array('data' => $objects, 'count' => $num_rows);
        }
    }

}
